package cn.changeforyou.web.blog.service.impl;

import cn.changeforyou.web.blog.po.User;
import cn.changeforyou.web.blog.service.IpAddressService;
import cn.changeforyou.web.blog.service.UseService;
import cn.changeforyou.web.nutz.common.exception.Asserts;
import cn.changeforyou.web.nutz.common.security.JwtTokenUtil;
import cn.hutool.crypto.SecureUtil;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;

/**
 * @author zhyu
 * @date 2021/3/19 18:04
 */
@IocBean
@Slf4j
public class UseServiceImpl implements UseService {

    @Inject
    private Dao dao;
    @Inject
    private IpAddressService ipAddressService;
    @Inject
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public NutMap login(User user) {
        List<User> users = dao.query(User.class, Cnd.where("username", "=", user.getUsername()));
        if (users.isEmpty()) {
            Asserts.fail("用户不存在");
        }
        User po = users.get(0);
        if (!SecureUtil.md5(user.getPassword()).equals(po.getPassword())) {
            Asserts.fail("密码错误");
        }
        String token = jwtTokenUtil.generateTokenFromUser(po);
        log.info("{} 登录成功", user.getUsername());
        ipAddressService.update(user.getId());
        return NutMap.NEW().setv("user", user).setv("token", token);
    }

}
